(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ?
        module.exports = factory() :
        typeof define === 'function' && define.amd ?
            define(factory) : (global = global || self, global.We = factory());
}
(this, function () {

    function We(options) {
        this._init(options);
    }

    var el;//渲染节点 id
    var elDom; //获取 入口dom
    function initMixin() {
        function setData(vm, data) {
            for (var name in data) {
                vm[name] = data[name];
            }
        }
        We.prototype._init = function (options) {
            el = options.el;
            elDom = document.querySelector(el);
            this.elDom = elDom;
            var vm = this;
            setData(vm, options.data());
            this._watch(options.data());
            createMounted(vm, options);
            var app = getOuterHTML(elDom);
        };
    }

    //获取template模板
    function getOuterHTML (el) {
        if (el.outerHTML) {
            return el.outerHTML;
        } else {
            var dom = document.createElement('div');
            dom.appendChild(el.cloneNode(true));
            return dom.innerHTML;
        }
    }

    // 监听对象属性
    function observer(target) {
        if (typeof target !== 'object' || target === null) {
            // 不是对象或数组
            return target
        }
        // 重新定义各个属性（for in 也可以遍历数组）
        for (var key in target) {
            defineReactive(target, key, target[key])
        }
    }

    // 重新定义属性，监听起来
    function defineReactive(target, key, value) {
        // 深度监听
        observer(value);
        // 核心 API
        Object.defineProperty(target, key, {
            get() {
                return value
            },
            set(newValue) {
                if (newValue !== value) {
                    // 深度监听
                    observer(newValue);
                    // 设置新值
                    // 注意，value 一直在闭包中，此处设置完之后，再 get 时也是会获取最新的值
                    value = newValue;
                    // 触发更新视图
                    console.log('视图更新');
                    // updateView()
                }
            }
        })
    }

    function initWatch() {
        We.prototype._watch = function (data) {
            if (Array.isArray(data)) {
                data.__proto__ = data;
            }
            var vm = this;
            for (var key in data) {
                defineReactive(vm, key, vm[key]);
            }
        }
    }

    function createMounted(vm, options) {
        vm.mounted = function () {
            return options.mounted.call(vm);
        };
        vm.mounted();
    }

    //模仿vue的use功能
    function initUse() {
        We.use = function (factoryFn) {
            We.prototype[factoryFn.name] = factoryFn;
        };
    }
    initUse();
    initWatch();
    initMixin();
    return We;
}));
